package generate

import (
	"fmt"
	"gorm.io/driver/postgres"
	"gorm.io/gen"
	"gorm.io/gorm"
	"strings"
)

// GenDbModel generate code
func GenDbModel(path, tablePrefix string) {
	g := gen.NewGenerator(gen.Config{
		OutPath:           path,
		Mode:              gen.WithoutContext, // Optional: can use context or not
		FieldWithIndexTag: true,               // Add index tag
		FieldWithTypeTag:  true,               // Add type tag
	})

	// Custom field type mapping
	dataMap := map[string]func(columnType gorm.ColumnType) string{
		"int": func(columnType gorm.ColumnType) string {
			return "int"
		},
		"tinyint": func(columnType gorm.ColumnType) string {
			return "int"
		},
	}
	// 172.16.0.11
	// QgnpJk8eopt7Fv2..

	// Apply custom data type mappings
	g.WithDataTypeMap(dataMap)

	// PostgreSQL database connection string
	//dbUrl := "postgres://postgres:QgnpJk8eopt7Fv2..@127.0.0.1:5435/xiuxian_db?sslmode=disable"

	dbUrl := "postgres://xlkj:QgnpJk8eopt7Fv2..@127.0.0.1:5436/xialou_platform?sslmode=disable"
	db, err := gorm.Open(postgres.Open(dbUrl), &gorm.Config{})
	if err != nil {
		fmt.Printf("failed to connect database: %v\n", err)
		return
	}
	g.UseDB(db)

	// Retrieve all table names from the database
	var tableNames []string
	err = db.Raw(`SELECT tablename FROM pg_tables WHERE schemaname = 'public'`).Scan(&tableNames).Error
	if err != nil {
		fmt.Printf("failed to retrieve table names: %v\n", err)
		return
	}

	// Filter tables by prefix and generate models only for tables with the specified prefix
	var filteredTables []interface{}
	for _, tableName := range tableNames {
		if strings.HasPrefix(tableName, tablePrefix) {
			model := g.GenerateModel(tableName)
			if model == nil {
				fmt.Printf("Failed to generate model for table: %s\n", tableName)
				continue
			}
			// g.ApplyBasic(model) // 应用CRUD功能
			filteredTables = append(filteredTables, model)
		}
	}

	// Apply basic CRUD API for the filtered tables
	g.ApplyBasic(filteredTables...)
	g.ApplyInterface(func() {})

	// Execute the code generation
	g.Execute()
}

func AutoMigrate() {
	// 数据库连接字符串
	dsn := "postgres://postgres:123456@127.0.0.1:5432/xiuxian_db?sslmode=disable"
	// 初始化数据库连接
	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("Failed to connect to database:", err)
		return
	}

	// 自动迁移模型到数据库
	err = db.AutoMigrate(
	//&model.AuctionBidLog{},
	//&model.AuctionBidRule{},
	//&model.AuctionCategory{},
	//&model.AuctionDailySchedule{},
	//&model.AuctionItem{},
	//&model.AuctionItemInstance{},
	//&model.AuctionOrder{},
	//&model.AuctionSession{},
	)
	if err != nil {
		fmt.Println("Failed to migrate database:", err)
		return
	}

	fmt.Println("Database migration completed successfully")
}
